package client.layer;

import server.layer.Person;

import javax.swing.table.AbstractTableModel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class MyModel extends AbstractTableModel {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.mm.yyyy");
    static ArrayList<Person> personList = new ArrayList<Person>();
    String[] headers = {"person_id", "First Name", "Last Name", "Birth Date", "File Path", "email" };

    public MyModel(ArrayList<Person> persons) {
        super();
        this.personList = persons;

    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Person person = personList.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return person.getPerson_id();
            case 1:
                return person.getFirstName();
            case 2:
                return person.getLastName();
            case 3:
                return person.getBirthDate() != null ? DATE_FORMAT.format(person.getBirthDate()) : "";
            case 4:
                return person.getFileName();
            case 5:
                return person.geteMail();
        }
        return "";
    }

    public int getRowCount() {
        return personList.size();
    }

    public int getColumnCount() {
        return headers.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return headers[columnIndex];
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return column != 0 && column != 4;
    }

    @Override
    public void setValueAt(Object value, int row, int column) {
        switch (column) {
            case 0:
                break;
            case 1:
                if (InputValidator.nameCheckValid((String) value)) {
                    personList.get(row).setFirstName((String) value);
                } else {
                }
                break;
            case 2:
                if (InputValidator.nameCheckValid((String) value)) {
                    personList.get(row).setLastName((String) value);
                } else {
                }
                break;
            case 3:
                if (InputValidator.dateCheckValid((String) value)) {
                    try {
                        personList.get(row).setBirthDate(DATE_FORMAT.parse((String) value));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 4:
                personList.get(row).setFileName((String) value);
                break;
            case 5:
                if (InputValidator.emailCheckValid((String) value)) {
                    personList.get(row).seteMail((String) value);
                }
                break;
        }
    }
}
